package com.weiyan.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.ByteBuffer;
import java.util.List;

/**
 * @author misterWei
 * @create 2020年02月27号:16点27分
 * @mailbox mynameisweiyan@gmail.com
 * 全局过滤器
 */
/*@Component*/
@Slf4j
public class AuthGlobalFilter implements GlobalFilter,Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            List<String> tokens = exchange.getRequest().getHeaders().get("token");
            if (tokens ==  null){
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.OK);
                ByteBuffer wrap = ByteBuffer.wrap("{\"code\":\"501\"}".getBytes("utf-8"));
                wrap.slice();
                DataBuffer dataBuffer = response.bufferFactory().wrap(wrap);
                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
              return   response.writeWith(Mono.just(dataBuffer));
            }
            log.warn("token = {}",tokens);
        }catch (Exception e){
            log.error("{}",e);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
